package com.cloud.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cloud.common.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

/**
 * packageName com.cloud.order.exception
 *
 * @author yanshuanglong
 * @version JDK 8
 * @className MyBlockExceptionHandler
 * @date 2025/3/20
 * @description wbe访问的sentinel异常处理
 */
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       String resourceName, BlockException e) throws Exception {
        response.setStatus(429);//请求量过大
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Result error = Result.error(resourceName + " 被限制Sentinel限制了，原因：" + e.getClass());
        writer.write(objectMapper.writeValueAsString(error));
        writer.flush();
        writer.close();
    }
}
